package jaux.tank.api.interceptor;

import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;

import jaux.tank.admin.config.properties.TankProperties;
import jaux.tank.bean.core.ShiroUser;
import jaux.tank.dao.cache.TokenCache;
import jaux.tank.shiro.ShiroKit;
import jaux.tank.utils.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 安全校验拦截器<br>
 * 判断非登录请求,将其定位置登录页面
 *
 */
@Component
public class SecurityInterceptor implements HandlerInterceptor {

	private Logger logger = Log.get(this.getClass());
	
	private final TokenCache tokenCache;
	private final TankProperties tankProps;

	SecurityInterceptor(TokenCache tokenCache, TankProperties tankProps) {
        this.tokenCache = tokenCache;
        this.tankProps = tankProps;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.info("requestURL:({}){}" ,request.getMethod(), request.getRequestURL() );

        //如果用户是非登录用户，则拒绝用户请求
        String method = request.getMethod();
        if("OPTIONS".equals(method) ||ShiroKit.isAuthenticated()){
            return true;
        }
        
        String token = ShiroKit.getRequestToken();
    	if (token == null) {
            this.printResponse(httpServletResponse);
            return false;
        }
        String shiroUserId = request.getHeader("shiroUserId");
        if(StringUtils.isEmpty(shiroUserId)) {
        	shiroUserId = request.getParameter("shiroUserId");
        }
        ShiroUser user = tokenCache.getUser(token);
		if (user == null
				||( !user.getSessionId().equals(request.getSession().getId()) 
						&& !user.getId().equals(shiroUserId))) {
            this.printResponse(httpServletResponse);
            return false;
        }
        return true;
    }


    private void printResponse(HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setStatus(401);
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.debug("done requestURL:({}){}", httpServletRequest.getMethod(), httpServletRequest.getRequestURL() );
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
      	logger.debug("complete requestURL:({}){}", httpServletRequest.getMethod(), httpServletRequest.getRequestURL() );
    }
}